<?php

/*
 *	Framework namespace
 */
namespace Nano
{
	/*
	 *	Upload controller class
	 *
	 *	@extends	\Kernel
	 */
	class Upload extends \Kernel
	{
		/*
		 *	$path	string	Path for uploads (relative to application path)
		 *
		 *	@private
		 */
		private $path = 'uploads';
		
		/*
		 *	$files	array	List of uploaded files
		 *
		 *	@private
		 */
		private $files = array();
		
		/*
		 *	Constructor
		 */
		public function __construct()
		{
			$this->path = APPLICATION.DS.$this->path;
			
			$this->check();
		}
		
		/*
		 *	Clear uploads. Be carful with it!
		 */
		public function clear()
		{
			return Filesystem::clear($this->path);
		}
		
		/*
		 *	Check for uploaded files
		 *
		 *	@return	array	Array with list of uploaded files
		 *	@return	false	If files does not submited
		 */
		public function check()
		{
			if(empty($_FILES))
			{
				debug(__CLASS__.': No uploaded files');
				
				return false;
			}
			
			if(!Filesystem::is('dir', $this->path))
			{
				throw new \Exception(__CLASS__.': Uploads directory does not exists');
			}
			
			if(!Filesystem::is('writeable', $this->path))
			{
				throw new \Exception(__CLASS__.': Uploads directory is not writeable');
			}
			
			foreach($_FILES as $parent => $data)
			{
				if(is_array($data['name']))
				{
					foreach($data['name'] as $num => $name)
					{
						$this->files[$parent][$num] = array
						(
							'name' => $name,
							'type' => $data['type'][$num],
							'tmp_name' => $data['tmp_name'][$num],
							'error' => $data['error'][$num],
							'size' => $data['size'][$num],
						);
					}
				}
				else
				{
					$this->files[$name] = $data;
				}
			}
			
			$this->save();
			
			return $this->files;
		}
		
		/*
		 *	Get progress of upload. Use via ajax.
		 *
		 *	@param	string	Id of upload
		 *	@return	array	Upload progress 
		 */
		public function progress($uid)
		{
			return (array)uploadprogress_get_info($uid);
		}
		
		/*
		 *	Save uploaded files
		 *
		 *	@private
		 */
		private function save()
		{
			foreach($this->files as $parent => $files)
			{
				foreach($files as $num => $data)
				{
					Filesystem::move($data['tmp_name'], $this->path.DS.$data['name']);
				}
			}
		}
	}
}